package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CourseBaseDto;
import com.xuecheng.commons.model.dto.CourseDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.CourseAuditDto;
import com.xuecheng.commons.model.vo.CourseBaseVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioProperties;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mappers.CourseBaseMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.system.web.exception.BusinessException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-16
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioProperties minioProperties;
    @Autowired
    CourseBaseService courseBaseService;
    @Autowired
    TeachplanService teachplanService;


    @Override
    public ResponseResult courseList(PageRequest request, CourseDto dto) {
        Page<CourseBase> pageParm = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<CourseBase> qw = new LambdaQueryWrapper<>();
        String courseName = dto.getCourseName();
        if (!StringUtils.isEmpty(courseName)){
            qw.like(CourseBase::getName,"%"+courseName+"%");
        }
        String auditStatus = dto.getAuditStatus();
        if (!StringUtils.isEmpty(auditStatus)){
            qw.eq(CourseBase::getAuditStatus,auditStatus);
        }
        String teachmode = dto.getTeachmode();
        if (!StringUtils.isEmpty(teachmode)){
            qw.eq(CourseBase::getTeachmode,teachmode);
        }
        qw.eq(CourseBase::getCompanyId, AuthInfoHolder.getCompanyId());
        IPage<CourseBase> Ipage = this.page(pageParm, qw);
        return PageResponseResult.okResult(Ipage.getTotal(),Ipage.getRecords());
    }

    //上传封面图片
    @Override
    public ResponseResult upload(MultipartFile uploadFile)throws Exception {
        InputStream stream = uploadFile.getInputStream();
        String filepath = "/images/"+new SimpleDateFormat("yyyy/MM/dd/")
                .format(new Date()) +
                UUID.randomUUID().toString()+uploadFile.getOriginalFilename();
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(filepath)
                .bucket(minioProperties.getBucket())
                .stream(stream,stream.available(),-1)
                .contentType("image/jpg")
                .build();
minioClient.putObject(putObjectArgs);
String urlpath=minioProperties.getDomain()+"/"+minioProperties.getBucket()+filepath;
return ResponseResult.okResult(urlpath);
    }

    //保存
    @Override
    public ResponseResult saveCourseBase(CourseBaseDto dto) {
        CourseBase courseBase = BeanHelper.copyProperties(dto, CourseBase.class);
        courseBase.setCompanyName(AuthInfoHolder.getAuthInfo().getCompanyName());
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);
        courseBase.setStatus(CommonConstants.USING_FLAG);
        courseBase.setCreateDate(new Date());
        courseBase.setPlanNum(0);
        boolean save = this.save(courseBase);
        if (!save){
throw new BusinessException(ErrorCode.ADDEERROR);
        }
      //初始化一个课程一级大纲(空着)
        Teachplan teachplan = new Teachplan();
        teachplan.setPname(courseBase.getName());
        teachplan.setParentid((long) 01);//强转可能出错
        teachplan.setGrade(CourseConstants.FIRST_LEVEL);
        teachplan.setCourseId(courseBase.getId());
        teachplan.setStatus(CourseConstants.FIRST_LEVEL);
        teachplan.setCreateDate(new Date());
        teachplanService.save(teachplan);
        Map map=new HashMap();
        map.put("courseBaseId",courseBase.getId());
       return ResponseResult.okResult(map);
    }


    @Override
    public ResponseResult updateCourseBase(CourseBaseDto dto) {
       //根据id查询课程数据
        CourseBase courseBase = this.getById(dto.getId());
        if (courseBase==null){
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        String auditStatus = courseBase.getAuditStatus();
        if (!CourseConstants.AUDIT_DISPAST_STATUS.equals(auditStatus)&&!CourseConstants.AUDIT_UNLINE_STATUS.equals(auditStatus)){
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        //修改课程
        CourseBase course = BeanHelper.copyProperties(dto, CourseBase.class);
        boolean update = this.updateById(course);
        if (!update){
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        Map map=new HashMap();
        map.put("courseBaseId",dto.getId());
        return ResponseResult.okResult(ErrorCode.ADDEERROR);

    }
//修改课程
    @Override
    public ResponseResult updateCourse(CourseBaseDto dto) {
        Long id = dto.getId();
        CourseBase courseBase = this.getById(id);
        if (courseBase==null){
throw new BusinessException(ErrorCode.NOTFOUND);
        }
        String status = courseBase.getAuditStatus();
        if (status.equals(CourseConstants.AUDIT_COMMIT_STATUS)||
        status.equals(CourseConstants.AUDIT_PASTED_STATUS)||
        status.equals(CourseConstants.AUDIT_PUBLISHED_STATUS)){
throw new BusinessException(ErrorCode.UPDATEEERROR);
        }

        //更新数据
        CourseBase updateCourse = BeanHelper.copyProperties(dto, CourseBase.class);
        boolean update = this.updateById(updateCourse);
        if (!update){
            throw new BusinessException(ErrorCode.ERROR);
        }
        Map map=new HashMap();
        map.put("courseBaseId",id);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult commit(Long courseBaseId) {

        CourseBase courseBase = this.getById(courseBaseId);
        if (courseBase==null){
throw new BusinessException(ErrorCode.NOTFOUND);
        }
        courseBase.setAuditStatus(CourseConstants.AUDIT_COMMIT_STATUS);
        boolean update = this.updateById(courseBase);
        if (!update){
throw new BusinessException(ErrorCode.ERROR);
        }
        return ResponseResult.okResult(null);
    }

    @Override
    public ResponseResult approve(CourseAuditDto dto) {

        CourseBase courseBase = this.getById(dto.getCourseBaseId());
        if (courseBase==null){
throw new BusinessException(ErrorCode.NOTFOUND);
        }
        courseBase.setAuditStatus(dto.getAuditStatus());
        courseBase.setAuditMind(dto.getAuditMind());
        boolean update = this.updateById(courseBase);
        if (!update){
throw new BusinessException(ErrorCode.ERROR);

        }return ResponseResult.okResult(null);
    }

//   @GetMapping("/{courseBaseId}")
//   public ResponseResult findBuId(@PathVariable("courseBaseId")Long courseBaseId){
//   CourseBase courseBase = courseBaseService.getById(courseBaseId);
//   CourseBaseVo vo = BeanHelper.copyProperties(courseBase, CourseBaseVo.class);
//   return ResponseResult.okResult(vo);
//
}
